package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.event.UserNicknameChangeEvent;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.PersonalCenterViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;

/**
 * 修改昵称
 */
public class ModifyNicknameActivity extends BaseActivity {

    @Bind(R.id.affirm_button) View mAffirmButton;
    @Bind(R.id.nickname_text_view) EditText mNicknameEdit;

    private PersonalCenterViewModel mViewModel;

    public static void launch(Context context, String nickname) {
        context.startActivity(new Intent(context, ModifyNicknameActivity.class)
                .putExtra(C.EXTRA_NICKNAME, nickname)
        );
    }

    @Override
    protected int getLayoutID() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        return R.layout.activity_modify_nickname;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_modify_nickname);
        mNicknameEdit.setHint(getIntent().getStringExtra(C.EXTRA_NICKNAME));

        // view model
        mViewModel = ViewModelProviders.of(this).get(PersonalCenterViewModel.class);
        mAffirmButton.setOnClickListener(v -> modifyNickname());
    }

    private void modifyNickname() {
        String nickname = mNicknameEdit.getText().toString();
        mViewModel.modifyNickname(nickname).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING){
                Androids.showProgressMessage(this, R.string.message_changing_nickname);
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);

                if (resource.state == Resource.Status.SUCCESS){
                    EventBus.getDefault().post(new UserNicknameChangeEvent(nickname));
                    finish();
                }
            }
        });
    }
}
